// pages/room5/storyForMinePage/storyForMinePage.js
import room4TestData from "../../testData/testR4Data";
const app = getApp();
var mfApi = require('../../../api/api.js');
let ZW_Ctx = null;
let ZW_Canvas = null;

var ZW_isLoading = false;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: app.globalData.baseUrl,
        /**
         * 房间资源
         */
        roomResourceData: room4TestData,

        currentStory: 0,

        storyData: [],

        shotImageUrl: null
    },

    onShareTimeline: function () {

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            canvasWidth: 750 * 0.4, // 300
            canvasHeight: 1624 * 0.4, // 650
            top: app.menu.top,
            h: app.menu.height
        })
    },

    onReady() {
        const query = wx.createSelectorQuery()
        query.select('#indexcanvas')
            .fields({
                node: true,
                size: true
            })
            .exec((res) => {
                ZW_Canvas = res[0].node
                ZW_Ctx = ZW_Canvas.getContext('2d')

                const dpr = wx.getSystemInfoSync().pixelRatio
                ZW_Canvas.width = res[0].width * dpr
                ZW_Canvas.height = res[0].height * dpr
                ZW_Ctx.scale(dpr, dpr)
            })
    },

    onShow() {
        setTimeout(() => {
            this.getStoryDataApi()
        }, 500);
    },

    async getStoryDataApi() {
        wx.showLoading({
            title: "加载中",
        });
        let res = await mfApi.http(mfApi.getStoryList(app.globalData.openId), "GET", {});
        if (res.code != 200) {
            wx.hideLoading();
            wx.showToast({
                icon: "none",
                title: '后端服务异常',
            })
            return;
        };

        this.setData({
            storyData: res.result
        })
        wx.hideLoading();

        //await this.drawCanvas();

    },

    async onSwiperChange(e) {
        let {
            current
        } = e.detail
        this.setData({
            currentStory: current,
            shotImageUrl: null
        })

        // wx.showToast({
        //     icon: "none",
        //     title: '当前卡片为'+current,
        // })

        //await this.drawCanvas();
    },

    onShareAppMessage(object) {
        if (object.from == "menu") {
            return {
                title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
                path: `/pages/index/index?inChannel=commonShare`,
                imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
            }
        }

        app.saveTrack(`R5-我的证书-分享`);
        return {
            title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
            path: `/pages/index/index?toPage=showStory&storyId=${this.data.storyData[this.data.currentStory].id}`,
            imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
        }
    },

    async onSaveClick() {
        wx.showLoading({
            title: "加载中",
        });
        if (ZW_isLoading) return;
        ZW_isLoading = true;
        app.saveTrack(`R5-我的证书-保存本地`);
        await this.drawCanvas();
        // let re = await this.shotCanvasImage();
        // if (re.code != 0) {
        //     wx.showToast({
        //         icon: "none",
        //         title: '海报生成失败',
        //     })
        //     wx.hideLoading();
        //     return;
        // }

        // wx.saveImageToPhotosAlbum({
        //     filePath: this.data.shotImageUrl,
        //     success: data => {
        //         wx.showToast({
        //             title: '保存成功',
        //         })
        //         wx.hideLoading();
        //     },
        //     fail: err => {
        //         wx.showToast({
        //             title: '保存失败',
        //             icon: "none"
        //         })
        //         wx.hideLoading();
        //     }
        // })
    },

    async drawCanvas() {
        let _self = this;
        let storyInfoData = this.data.storyData[this.data.currentStory]
        // 获取小程序二维码
        let qrRes = await mfApi.http(mfApi.genQrcode(), "POST", {
            "auto_color": true,
            "check_path": false,
            "env_version": "develop",
            "is_hyaline": false,
            "page": "pages/index/index",
            "scene": `storyId//${storyInfoData.id}`,
            "width": 500
        })

        console.log(qrRes)
        if (qrRes.code != 200) {
            wx.showToast({
                icon: "none",
                title: '后端服务异常',
            })
            return;
        }

        // canvas上的一堆图片
        let imageInfoData = [{
            des: "用户头像",
            type: "main",
            srcUrl: storyInfoData.avatar ? storyInfoData.avatar : _self.data.baseUrl + '/room5/user.png',
            posx: 27,
            posy: 69,
            width: 48,
            height: 48,
            cornerTopLeft: 24,
            cornerTopRight: 24,
            cornerBottomLeft: 24,
            cornerBottomRight: 24,
        }, {
            des: "副标题",
            srcUrl: `${_self.data.baseUrl}/room5/result-title.png`,
            posx: 54,
            posy: 139,
            width: 191,
            height: 22
        }, {
            des: "主图",
            type: "main",
            scaleNeed: true,
            srcUrl: `${storyInfoData.storyImgUrl}`,
            posx: 60,
            posy: 210,
            width: 180,
            height: 195,
            cornerTopLeft: 45,
            cornerTopRight: 45,
            cornerBottomLeft: 10,
            cornerBottomRight: 20,
        }, {
            des: "主图外框",
            srcUrl: `${_self.data.baseUrl}/room5/image-frame.png`,
            posx: 56,
            posy: 205,
            width: 213,
            height: 257
        }, {
            des: "底部外框",
            srcUrl: `${_self.data.baseUrl}/room5/result-zhengshu-bottom.png`,
            posx: 0,
            posy: 557,
            width: 303,
            height: 95
        }, {
            des: "二维码",
            type: "main",
            srcUrl: qrRes.result.fileUrl,
            posx: 222,
            posy: 566,
            width: 60,
            height: 60,
            cornerTopLeft: 30,
            cornerTopRight: 30,
            cornerBottomLeft: 30,
            cornerBottomRight: 30,
        }]

        let bgData = {
            des: "bg",
            srcUrl: _self.data.baseUrl + _self.data.roomResourceData.showBackgroundImage,
            posx: 0,
            posy: 0,
            width: 350,
            height: 700
        }

        await this.canvasDrawImage(bgData)

        // ios需要往下挪一点
        let tempS = app.system.system.toLowerCase();
        let isContain = tempS.includes("ios");

        // 证书编号
        ZW_Ctx.font = "9px LaMerHeadlineWhiteItalic";
        let zlen0 = ZW_Ctx.measureText(`NO.${storyInfoData.storyNum}`).width;
        ZW_Ctx.font = "9px LaMerHeadlineWhiteItalic";
        ZW_Ctx.textBaseline = 'top';
        ZW_Ctx.fillStyle = "rgb(91, 113, 118)";
        ZW_Ctx.fillText(`NO.${storyInfoData.storyNum}`, 300 - (zlen0) - 40, 76);

        // user  白线
        let temp = {
            des: "底部外框标题",
            srcUrl: `${_self.data.baseUrl}/room5/story-line.png`,
            posx: 84,
            posy: isContain ? 78 : 81,
            width: 280 - 26 - 26 - 48 - 18 - (zlen0),
            height: 0.5
        };
        imageInfoData.push(temp);

        // 内容线
        let tempLine = {
            des: "内容分割线",
            srcUrl: `${_self.data.baseUrl}/room5/story-line.png`,
            posx: 55,
            posy: 462,
            width: 300 - 110,
            height: 0.5
        };
        imageInfoData.push(tempLine);

        // 副标题 三段组成
        ZW_Ctx.font = "12px Arial";
        ZW_Ctx.textBaseline = 'top';
        ZW_Ctx.fillStyle = 'rgb(55, 55, 55)';
        let len0 = ZW_Ctx.measureText("感 谢 你 成 为 第").width;
        let len2 = ZW_Ctx.measureText("位 参 展 人").width;

        ZW_Ctx.font = "14px LaMerHeadlineWhiteItalic";
        ZW_Ctx.textBaseline = 'top';
        ZW_Ctx.fillStyle = 'rgb(55, 55, 55)';
        let len1 = ZW_Ctx.measureText(` ${storyInfoData.positionNum} `).width;

        // part0
        ZW_Ctx.font = "12px Arial";
        ZW_Ctx.fillText("感 谢 你 成 为 第", (300 - (len0 + len1 + len2)) / 2, 173);

        // part2
        ZW_Ctx.fillText("位 参 展 人", ((300 - (len0 + len1 + len2)) / 2) + len0 + len1, 173);

        // part1
        ZW_Ctx.textBaseline = 'top';
        ZW_Ctx.font = "14px LaMerHeadlineWhiteItalic";
        ZW_Ctx.fillStyle = 'rgb(55, 55, 55)';
        ZW_Ctx.fillText(` ${storyInfoData.positionNum} `, ((300 - (len0 + len1 + len2)) / 2) + len0, 172);

        // userName
        ZW_Ctx.font = "15px Arial";
        ZW_Ctx.fillText(`@${storyInfoData.nickName}`, 85, 87);

        // 故事内容
        let str0 = `《${storyInfoData.storyTitle}》`;
        let str1 = storyInfoData.storyDesc

        console.log(str0);
        console.log(str1);
        ZW_Ctx.font = "15px Arial";
        ZW_Ctx.textBaseline = 'top';
        ZW_Ctx.fillStyle = 'rgb(0, 0, 0)';
        ZW_Ctx.fillText(str0, 50, 441);

        ZW_Ctx.font = "10px Arial";
        ZW_Ctx.textBaseline = 'top';
        ZW_Ctx.fillStyle = 'rgb(0, 0, 0)';
        ZW_Ctx.fillText(str1, 55, 472);

        // let templeft = {};
        // templeft.srcUrl = _self.data.baseUrl + "/room5/sign-left.png";
        // templeft.posx = contentText0x - 25;
        // templeft.posy = 560;
        // templeft.width = 15;
        // templeft.height = 12;
        // imageInfoData.push(templeft);

        // let tempright = {};
        // tempright.srcUrl = _self.data.baseUrl + "/room5/sign-right.png";
        // tempright.posx = contentText1x - 10;
        // tempright.posy = 570;
        // tempright.width = 15;
        // tempright.height = 12;
        // if (str1.length > 0) {
        //     tempright.posx = contentText1x + str1Width + 10;
        //     tempright.posy = 590;
        // } else {
        //     tempright.posx = contentText0x + str0Width + 10;
        //     tempright.posy = 560;
        // }
        // imageInfoData.push(tempright);

        for (let i = 0; i < imageInfoData.length; i++) {
            console.log("draw  image  " + i)
            let re = null;
            if (imageInfoData[i].type && imageInfoData[i].type == "main")
                re = await this.canvasDrawMainImage(imageInfoData[i]);
            else
                re = await this.canvasDrawImage(imageInfoData[i])
            console.log(re)
        }

        let re = await this.shotCanvasImage();
        if (re.code != 0) {
            wx.showToast({
                icon: "none",
                title: '海报生成失败',
            })
            wx.hideLoading();
            return;
        }

        wx.saveImageToPhotosAlbum({
            filePath: this.data.shotImageUrl,
            success: data => {
                wx.showToast({
                    title: '保存成功',
                })
                ZW_isLoading = false;
                wx.hideLoading();
            },
            fail: err => {
                wx.showToast({
                    title: '保存失败',
                    icon: "none"
                })
                ZW_isLoading = false;
                wx.hideLoading();
            }
        })

    },

    canvasDrawImage(imageInfoData) {
        return new Promise(function (resolve, reject) {
            let tempImage = ZW_Canvas.createImage();
            tempImage.src = imageInfoData.srcUrl;
            tempImage.onload = () => {
                ZW_Ctx.drawImage(tempImage,
                    imageInfoData.posx,
                    imageInfoData.posy,
                    imageInfoData.width,
                    imageInfoData.height);

                resolve({
                    code: 0,
                })
            }
        })
    },

    canvasDrawMainImage(imageInfoData) {
        let _self = this;

        return new Promise(function (resolve, reject) {
            wx.getImageInfo({
                src: imageInfoData.srcUrl,
                success(res) {
                    console.log("getImageInfo === ", res)
                    let tempImage = ZW_Canvas.createImage();
                    tempImage.src = imageInfoData.srcUrl;

                    tempImage.onload = (e) => {
                        console.log("tempImage =-=-=-=-=-=-=")
                        ZW_Ctx.save();

                        let w = imageInfoData.width;
                        let h = imageInfoData.height;
                        let x = imageInfoData.posx;
                        let y = imageInfoData.posy;

                        let r = 20;
                        if (w < 2 * r) r = w / 2;
                        if (h < 2 * r) r = h / 2;
                        ZW_Ctx.beginPath();
                        ZW_Ctx.moveTo(x + r, y);
                        ZW_Ctx.arcTo(x + w, y, x + w, y + h, imageInfoData.cornerTopRight);
                        ZW_Ctx.arcTo(x + w, y + h, x, y + h, imageInfoData.cornerBottomRight);
                        ZW_Ctx.arcTo(x, y + h, x, y, imageInfoData.cornerBottomLeft);
                        ZW_Ctx.arcTo(x, y, x + w, y, imageInfoData.cornerTopLeft);

                        ZW_Ctx.closePath();
                        ZW_Ctx.clip();

                        if (imageInfoData.scaleNeed == false) {
                            ZW_Ctx.drawImage(tempImage,
                                imageInfoData.posx,
                                imageInfoData.posy,
                                imageInfoData.width,
                                imageInfoData.height);
                        } else {
                            let imgX = imageInfoData.posx; //图片在画布上的x轴坐标
                            let imgY = imageInfoData.posy; //图片在画布上的y轴坐标
                            let imgW = imageInfoData.width; //图片在画布上的宽度
                            let imgH = imageInfoData.height; //图片在画布上的高度

                            let visibleW = res.width //截取的图片的宽度
                            let visibleH = res.height //截取的图片的高度
                            let visibleX = null // 所截取的图片的x轴坐标
                            let visibleY = null // 所截取的图片的y轴坐标

                            let imgBili = imgW / imgH
                            let visibleBili = visibleW / visibleH
                            if (imgBili < visibleBili) {
                                let newW = (imgH / visibleH) * visibleW
                                const bili = newW / visibleW
                                visibleX = Math.abs(imgW - newW) / 2 / bili
                                visibleY = 0
                                visibleW = imgW * visibleH / imgH
                            } else {
                                visibleX = 0
                                let newH = (imgW * visibleH) / visibleW
                                const bili = newH / visibleH
                                visibleY = Math.abs(imgH - newH) / 2 / bili
                                visibleH = visibleW * imgH / imgW
                            }

                            ZW_Ctx.drawImage(tempImage, visibleX, visibleY, visibleW, visibleH, imgX, imgY, imgW, imgH)
                        }

                        ZW_Ctx.restore();

                        resolve({
                            code: 0,
                        })
                    }
                }
            })

        })
    },

    shotCanvasImage(inType) {
        let _self = this;
        return new Promise((resolve, reject) => {

            setTimeout(() => {
                wx.canvasToTempFilePath({
                    canvas: ZW_Canvas,
                    success: (res) => {
                        console.log("shotQrCode === ", res)
                        _self.setData({
                            shotImageUrl: res.tempFilePath
                        })
                        resolve({
                            code: 0,
                        })
                    },
                    fail: err => {
                        console.log("shotQrCode === err ", err)
                    }
                })
            }, 20);


        })
    },

    goBack() {
        wx.navigateBack();
    }
})